import { getValidDate } from '@/dataTransfer/coupon';
import { debounce } from '@/utils/helper.js';
import { dateFormat } from '@/utils/time';
import { Image, ScrollView, View } from '@tarojs/components';
import React, { useCallback, useEffect, useState } from 'react';
import { connect } from 'react-redux';
import Advert from '../../pages/advert';
import pHeader from '../images/newShopTimeline/header.png';
import './index.scss';
import LocationAuth from './locationAuth';
import ShopList from './shopList';

function transform(list = []) {
  const temp = list
    ?.map((item) => {
      const date = getValidDate(item.created);
      return {
        ...item,
        date,
        dateStr: dateFormat(date, 'yyyy/MM/dd'),
      };
    })
    ?.reduce((r, item) => {
      if (!r[item.dateStr]) {
        r[item.dateStr] = [];
      }

      r[item.dateStr].push(item);
      return r;
    }, {});

  return Object.keys(temp)
    .sort()
    .reverse()
    .map((key) => {
      return {
        dateStr: key,
        list: temp[key],
      };
    });
}

const NewShopTimeline = ({ dispatch, newShopOrgListFinished, newShopOrgList }) => {
  const [curLocation, setCurLocation] = useState(null);

  const list = transform(newShopOrgList);

  const getNextList = useCallback(() => {
    const { latitude, longitude } = curLocation ?? {};
    if (!latitude) {
      return;
    }

    return dispatch({
      type: 'otherApi/fetchNewShopOrgList',
      payload: {
        pageSize: 10,
        isLocal: 1,
        lat: latitude,
        lon: longitude,
        sortType: 4,
      },
    });
  }, [curLocation]);

  // 滚动获取
  const handleScrollToLower = debounce(() => {
    !newShopOrgListFinished && newShopOrgList?.length > 0 && getNextList();
  }, 1200);

  useEffect(() => {
    if (curLocation) {
      getNextList();
    }
  }, [curLocation]);

  return (
    <ScrollView
      className="NewShopTimeline"
      enableFlex
      scrollY
      onScrollToLower={handleScrollToLower}
    >
      <LocationAuth setCurLocation={setCurLocation} featureName="新品日历功能" />

      <View className="new-shop-header">
        <Image className="img" src={pHeader}></Image>
      </View>

      <View>
        <Advert prefix="jrdb" alias="_jrdb" goTxt="进店逛逛" />
      </View>

      {curLocation &&
        list?.map(({ dateStr, list: dataList }) => {
          return (
            <View key={dateStr} className="time-line-item">
              <View className="time-line-date">{dateStr.substr(5)} 新店</View>

              <ShopList dataList={dataList} />
            </View>
          );
        })}
    </ScrollView>
  );
};

export default connect(({ otherApi }) => ({
  newShopOrgList: otherApi.newShopOrgList,
  newShopOrgListFinished: otherApi.newShopOrgListFinished,
}))(NewShopTimeline);
